package com.xiaomo.gitee.datamanager.service.tag.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomo.gitee.datamanager.aspect.log.anno.SysLog;
import com.xiaomo.gitee.datamanager.mapper.CategoryTagMapper;
import com.xiaomo.gitee.datamanager.mapper.TagsMapper;
import com.xiaomo.gitee.datamanager.entity.ImageTag;
import com.xiaomo.gitee.datamanager.service.tag.ImageTagService;
import com.xiaomo.gitee.datamanager.mapper.ImageTagMapper;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ImageTagServiceImpl extends ServiceImpl<ImageTagMapper, ImageTag>
    implements ImageTagService{

    private final CategoryTagMapper categoryTagMapper;
    private final TagsMapper tagsMapper;
    private final ImageTagMapper imageTagMapper;

    @Override
    public List<ImageTag> getTagsOfImage(String imageId) {
        return imageTagMapper.selectAllByImageId(imageId);
    }

    @Override
    @SysLog("为图片添加标签")
    public boolean addTagToImage(String imageId, List<Long> tagsId) {
        QueryWrapper<ImageTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("image_id",imageId);
        queryWrapper.in("tag_id",tagsId);
        if (!imageTagMapper.selectList(queryWrapper).isEmpty()) {
            return false;
        }
        /*if (!imageTagMapper.selectByImageIdAndTagId(imageId, tagsId).isEmpty()) {
            return false;
        }*/
        List<ImageTag> imageTagList = tagsId.stream().map(tag -> new ImageTag(imageId,tag,false)).toList();
        imageTagMapper.insertBatch(imageTagList);
//        imageTagMapper.insert(new ImageTag(imageId, tagsId,false));

        return true;
    }

    @Override
    @SysLog("删除图片标签")
    public boolean deleteTagOfImage(String imageId, List<Long> tagsId) {
        QueryWrapper<ImageTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("image_id",imageId);
        queryWrapper.in("tag_id",tagsId);
        imageTagMapper.delete(queryWrapper);
//        imageTagMapper.deleteByImageIdAndTagId(imageId,tagsId);

        return true;
    }

    @Override
    public List<List<String>> getMultipleTags(List<String> imagesId) {
        List<List<String>> result = new ArrayList<>();
        for (String s : imagesId) {
            List<String> tags = imageTagMapper.selectAllByImageId(s).stream().map(imageTag ->
                    tagsMapper.selectOneById(imageTag.getTagId()).getContent()
            ).toList();
            result.add(tags);
        }
        return result;
    }


}




